package agentV1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"hc_server/pkg/app"
	"hc_server/pkg/sms"
	"hc_server/routers/service/codeService"
	"hc_server/runtime/e"
	"math/rand"
	"time"
)

type CodeAgentRegisterCodeForm struct {
	Mobile interface{} `json:"mobile"`
}

// CodeGetAgentRegisterCode 代理商注册获取验证码
func CodeGetAgentRegisterCode(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		form    CodeAgentRegisterCodeForm
		errCode int
	)
	_, errCode = app.BindJsonAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	if form.Mobile == "" {
		appG.ResponseError("手机号码不能为空", nil)
		return
	}

	codeService := codeService.Code{Mobile: form.Mobile, Type: 1, Ip: c.ClientIP(), Code: generateVerificationCode()}
	// 获取验证码数量超过3次限制发送
	err := codeService.GetCodeCount()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	//验证码入库
	err = codeService.AddCode()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	temp := &sms.Sms{PhoneNo: cast.ToString(form.Mobile),
		SignName:     "梵客Upay管家",
		TemplateCode: "SMS_264835858",
	}

	// 发送短信
	err = sms.SmsAliSend(temp)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("验证码发送成功", codeService.Code)
}

type CodeGetSalesmenRegisterCodeForm struct {
	Mobile interface{} `json:"mobile"`
}

// CodeGetSalesmenRegisterCode 代理商注册获取验证码
func CodeGetSalesmenRegisterCode(c *gin.Context) {
	appG := app.Gin{C: c}
	var (
		form    CodeGetSalesmenRegisterCodeForm
		errCode int
	)
	_, errCode = app.BindJsonAndValid(c, &form)
	if errCode != e.SUCCESS {
		appG.ResponseError(e.CodeMap[errCode], nil)
		return
	}

	if form.Mobile == "" {
		appG.ResponseError("手机号码不能为空", nil)
		return
	}

	codeService := codeService.Code{Mobile: form.Mobile, Type: 1, Ip: c.ClientIP(), Code: generateVerificationCode()}
	// 获取验证码数量超过3次限制发送
	err := codeService.GetCodeCount()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	//验证码入库
	err = codeService.AddCode()
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	temp := &sms.Sms{PhoneNo: cast.ToString(form.Mobile),
		SignName:     "梵客Upay管家",
		TemplateCode: "SMS_264835858",
	}

	// 发送短信
	err = sms.SmsAliSend(temp)
	if err != nil {
		appG.ResponseError(err.Error(), nil)
		return
	}

	appG.ResponseSuccess("验证码发送成功", codeService.Code)
}

func generateVerificationCode() string {
	// 使用时间作为种子来创建一个新的随机数生成器
	source := rand.NewSource(time.Now().UnixNano())
	random := rand.New(source)

	// 生成6位随机数
	codeStr := ""
	for i := 0; i < 6; i++ {
		codeStr += fmt.Sprintf("%d", random.Intn(10)) // 生成0到9的随机数
	}

	return codeStr
}
